package thread.optimisticlock;

public class TestLock {

	public static void main(String[] args) {
		LockObj obj = new LockObj();//对线程并发同一个实例
		Bean b = new Bean();
		b.setState(0);
		obj.setBean(b);
		
		MyThread t1 = new MyThread(obj);
		t1.setName("t1");
		MyThread t2 = new MyThread(obj);
		t2.setName("t2");
		MyThread t3 = new MyThread(obj);
		t3.setName("t3");
		t1.start();
		t2.start();
		t3.start();
		System.out.println("main thread is over");
	}

}
class MyThread extends Thread {
	private volatile LockObj obj;
	public MyThread(LockObj a) {
		this.obj = a;
	}
	@Override
	public void run() {
		System.out.println(currentThread().getName()+" is start");
		for(int i=1;i<=10000;i++){
			boolean result = false;
			while(!result){//如果结果为false则重试
				int currentVersion = obj.getVersion();//操作前获取当前version
				Bean b = new Bean();
				b.setState(obj.getBean().getState());
				result = obj.changeBean(currentVersion, b);//传入version进行校验
			}
		}
		System.out.println(currentThread().getName()+" is over bean is:"+this.obj.getBean().getState()+",version"
				+ ":"+this.obj.getVersion());
	}
}